package com.itheima.controller;

import com.itheima.bean.R;
import com.itheima.bean.ShoppingCart;
import com.itheima.config.BaseContext;
import com.itheima.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService ss;
    /**
     * 添加购物车
     * @param shoppingCart
     * @return 购物车
     */
    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart){
        //调用service
        //int row = ss.add(shoppingCart);
        ShoppingCart cart = ss.add(shoppingCart);

        /*if (row > 0) {
            return R.success("添加成功");
        } else {
            return R.error("添加失败");
        }*/
        try {
            return R.success(cart);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("添加购物车失败");
        }
    }

    /**
     * 按照用户的id来查询数据
     * @return
     */
    @GetMapping("/list")
    public R list(){

        //1、根据用户的id来查询这个用户的购物车数据
        List<ShoppingCart> cartList = ss.findAll(BaseContext.get());

        return R.success(cartList);
    }

    /**
     * 按照用户的id来清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    public R clean(){
        int row = ss.delete(BaseContext.get());
        if (row > 0){
            return R.success("清空购物车成功！");
        } else {
            return R.error("清空购物车失败！");
        }
    }
}
